package com.security.order.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.security.order.model.UserDTO;
import com.security.order.util.EncryptUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wangning
 * @create 2021-03-27 16:04
 */
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
									FilterChain filterChain) throws ServletException, IOException {
		String token = request.getHeader("json-token");
		if (token != null) {
			//1.解析token,将token转成json对象
			String json = EncryptUtil.decodeUTF8StringBase64(token);
			JSONObject userJson = JSON.parseObject(json);
			//用户身份信息
			String principal = userJson.getString("principal");
			//用户身份信息
			UserDTO userDTO = new UserDTO();
			userDTO.setUsername(principal);

			//用户权限
			JSONArray authoritiesArray = userJson.getJSONArray("authorities");
			String[] authorities = authoritiesArray.toArray(new String[authoritiesArray.size()]);

			//2.新建并填充authentication
			UsernamePasswordAuthenticationToken authentication =
					new UsernamePasswordAuthenticationToken(userDTO, null, AuthorityUtils.createAuthorityList(authorities));
			authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
			//3.将authentication保存进安全上下文
			SecurityContextHolder.getContext().setAuthentication(authentication);
		}
		//因为这是一个过滤器链，所以需要继续走
		filterChain.doFilter(request, response);
	}
}